package postgres

import (
	"context"
	"fmt"
	"quipus/internal/database/model"

	apb "quipus/proto/gen/assist"

	_ "github.com/jackc/pgx/v5/stdlib"
	_ "github.com/joho/godotenv/autoload"
	"github.com/pkg/errors"
)

func (p *PGDB) CreateTopic(ctx context.Context, create *model.Topic) error {
	p.query()
	qdo := q.WithContext(ctx)
	err := qdo.Topic.Create(create)
	if err != nil {
		return errors.Wrap(err, "failed to create topic")
	}
	return nil
}

func (p *PGDB) CreateTopicInBatchs(ctx context.Context, create []*model.Topic) error {
	p.query()
	qdo := q.WithContext(ctx)
	err := qdo.Topic.CreateInBatches(create, len(create))
	if err != nil {
		return errors.Wrap(err, "failed to create topics")
	}
	return nil
}

func (p *PGDB) ListTopics(ctx context.Context, find *apb.FindTopic) ([]*model.Topic, int32, error) {
	p.query()
	qdo := q.WithContext(ctx)
	topic := qdo.Topic

	if find.SubjectId > 0 {
		topic = topic.Where(q.Topic.SubjectID.Eq(find.SubjectId))
	}

	if find.KeyWords != nil {
		content := qdo.Topic

		for _, kw := range find.KeyWords {
			content = content.Where(q.Topic.Title.Like(fmt.Sprintf("%%%s%%", kw))).Or(content.Where(q.Topic.Summary.Like(fmt.Sprintf("%%%s%%", kw))))
		}
		topic = topic.Where(content)
	}

	limit := find.Limit
	if limit == 0 {
		limit = 10
	}

	topics, count, err := topic.FindByPage(int(find.Offset), int(limit))
	if err != nil {
		return nil, 0, err
	}

	return topics, int32(count), err
}

func (p *PGDB) DeleteTopic(ctx context.Context, delete *apb.DeleteTopic) error {
	p.query()
	qdo := q.WithContext(ctx)
	topic := qdo.Topic
	if delete.TopicId > 0 {
		topic = topic.Where(q.Topic.ID.Eq(delete.TopicId))
	}
	if delete.SubjectId > 0 {
		topic = topic.Where(q.Topic.SubjectID.Eq(delete.SubjectId))
	}
	_, err := topic.Delete()

	if err != nil {
		return err
	}

	return nil
}

func (p *PGDB) GetTopic(ctx context.Context, id int32) (*model.Topic, error) {
	p.query()
	qdo := q.WithContext(ctx)
	return qdo.Topic.Where(q.Topic.ID.Eq(id)).First()
}

func (p *PGDB) GetTopicUnits(ctx context.Context, parentId int32) ([]*model.Topic, error) {
	p.query()
	qdo := q.WithContext(ctx)
	return qdo.Topic.Where(q.Topic.ParentID.Eq(parentId)).Find()
}
